package com.example.neartweet;

import java.util.List;

import com.example.neartweet.ComService.LB;
import com.example.neartweet.TwitterApp.TwDialogListener;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class TweetAdapter extends BaseAdapter{

	private List<TweetItem> data;
	private Context context;
	private ViewHolder holder;
	private TwitterApp mTwitter;
	private String username = "";

	private ServiceConnection mConnection;
	ComService serv;
	
	private static final String twitter_consumer_key = "9bO9i0f0urTGfSx4LqNJA";
	private static final String twitter_secret_key = "nnBmT2sLwnsMbPMTdoWuOzRJRCJHPIfYdiIrub0DKQ";

	public OnLongClickListener myClickListener = new OnLongClickListener() {
		public boolean onLongClick(View v) {
			((ViewSwitcher) v).showNext();
			return true;
		}
	};

	public TweetAdapter(Context context, List<TweetItem> data) {
		this.context = context;
		this.data = data;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public TweetItem getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final TweetItem item = getItem(position);

		if (convertView == null) {
			LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = li.inflate(R.layout.tweet, parent, false);
			holder = new ViewHolder();
			holder.avatar = (QuickContactBadge) convertView.findViewById(R.id.avatar);
			holder.username = (TextView) convertView.findViewById(R.id.username);
			holder.tweet = (TextView) convertView.findViewById(R.id.msg);
			holder.location = (ImageView) convertView.findViewById(R.id.tweet_location);
			holder.bAction0 = (ImageButton) convertView.findViewById(R.id.details);
			holder.bAction1 = (ImageButton) convertView.findViewById(R.id.reply);
			holder.bAction2 = (ImageButton) convertView.findViewById(R.id.retweet);
			holder.bAction3 = (ImageButton) convertView.findViewById(R.id.flag);
			holder.switcher = (ViewSwitcher) convertView.findViewById(R.id.viewSwitcher);
			convertView.setTag(holder);
			convertView.setOnLongClickListener(myClickListener);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		mConnection = new ServiceConnection() {
			public void onServiceConnected(ComponentName className,
					IBinder service) {
				LB binder = (LB) service;
				serv = binder.getService();
			}
			public void onServiceDisconnected(ComponentName className) {

			}
		};

		mTwitter = new TwitterApp(context, twitter_consumer_key, twitter_secret_key);

		mTwitter.setListener(mTwLoginDialogListener);


		Intent intent = new Intent(context, ComService.class);
		context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

		holder.avatar.setImageDrawable(item.getAvatar());
		holder.username.setText(item.getUsername());
		holder.tweet.setText(item.getTweet());
		if (item.hasLocation())
			holder.location.setVisibility(View.VISIBLE);
		else
			holder.location.setVisibility(View.INVISIBLE);


		holder.bAction0.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, DetailsActivity.class);
				intent.putExtra("username", item.getUsername());
				intent.putExtra("msg", item.getTweet());
				if (item.hasLocation()) {
					intent.putExtra("lat", item.getLat());
					intent.putExtra("lon", item.getLon());
				}
				context.startActivity(intent);
			}
		});

		holder.bAction1.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, ComposeActivity.class);
				intent.putExtra("username", item.getUsername());
				context.startActivity(intent);
			}
		});

		holder.bAction2.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String review = item.getTweet().toString();
				postToTwitter(review);
			}
		});

		holder.bAction3.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences sharedPrefs = context.getSharedPreferences(
						context.getString(R.string.preference_file_key),context.MODE_PRIVATE);
				String uN = sharedPrefs.getString("usr", "");
				serv.ban(uN, item.getUsername());
			}
		});

		return convertView;
	}

	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			String text = (msg.what == 0) ? "Posted to Twitter" : "Post to Twitter failed";

			Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
		}
	};

	private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
		@Override
		public void onComplete(String value) {
			username    = mTwitter.getUsername();
			username    = (username.equals("")) ? "No Name" : username;

			Toast.makeText(context, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
		}

		@Override
		public void onError(String value) {

			Toast.makeText(context, "Twitter connection failed", Toast.LENGTH_LONG).show();
		}
	};

	private void postToTwitter(final String review) {
		new Thread() {
			@Override
			public void run() {
				int what = 0;

				try {
					mTwitter.updateStatus(review);
				} catch (Exception e) {
					what = 1;
				}

				mHandler.sendMessage(mHandler.obtainMessage(what));
			}
		}.start();
	}

	static class ViewHolder {
		ViewSwitcher switcher;
		QuickContactBadge avatar;
		TextView username;
		TextView tweet;
		ImageButton bAction0;
		ImageButton bAction1;
		ImageButton bAction2;
		ImageButton bAction3;
		ImageView location;
	}

}